package com.haiblee.aescipher;

import java.security.MessageDigest;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class HaibleeAES {
    public static void main(String[] args){
        try {
            String encryptResult = execute("this is my src content","123456789ABC",true);
            System.out.println("encryptResult : "+encryptResult+"\ndecryptResult : "+execute(encryptResult,"123456789ABC",false));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static String execute(String content,String password,boolean isEncrypt) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        final String key = parseByte2HexStr(md.digest(password.getBytes())).substring(8,24);
        final byte[] keyBytes = key.getBytes("UTF-8");
        if(isEncrypt){
            Cipher encryptCipher = Cipher.getInstance("AES");
            encryptCipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, "AES"));
            return parseByte2HexStr(encryptCipher.doFinal(content.getBytes("UTF-8")));
        }else{
            Cipher decryptCipher = Cipher.getInstance("AES");
            decryptCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, "AES"));
            return new String(decryptCipher.doFinal(parseHexStr2Byte(content)), "UTF-8") ;
        }
    }
    private static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) hex = '0' + hex;
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }
    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
}
